// ===============================================
// img_ex
// 拓展图片 主要是融合 本地图片 和网络图片
// Create by Will on 14/9/2023 12:00
// Copyright Will .All rights reserved.
// ===============================================

import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:vector_graphics/vector_graphics.dart';

import '../../assets/res.dart';
import 'network/img_ex_network_provider.dart';

class ImgEx extends StatelessWidget {
  const ImgEx({
    super.key,
    required this.url,
    this.width,
    this.height,
    this.fit = BoxFit.cover,
    this.onTap,
    this.color,
    this.radius = 0,
    this.borderRadius,
    this.always = false,
    this.useEncrypt = false,
    this.usingDynamicColor = true,
    this.loadingWidget,
    this.failedWidget,
    this.headers,
    this.border,
    this.aspectRatio = 0,
  });

  //图片的url 不管是不是本地都用url
  final String url;

  // 组件宽度
  final double? width;

  // 组件高度
  final double? height;

  // 图片显示模式
  final BoxFit? fit;

  final BorderRadius? borderRadius;

  // 图片的圆角
  final double radius;

  //点击事件
  final GestureTapCallback? onTap;

  //每次都获取最新图片僅在网络图片中生效
  final bool always;

  // 背景颜色
  final Color? color;

  ///是否啟用加解密
  final bool useEncrypt;

  final bool usingDynamicColor;

  //加载时使用的loading
  final Widget? loadingWidget;

  //失败时使用的图片
  final Widget? failedWidget;

  //请求头
  final Map<String, String>? headers;

  //边框
  final BoxBorder? border;

  //采用的宽高比 一旦采用图片将不受 fit 和宽高使用
  final double aspectRatio;

  @override
  Widget build(BuildContext context) {
    Widget child = Image.asset(
      Res.imagesUserIcImageDefault,
      // Res.imagesUserVideoDefaultBackground,
      fit: fit,
      width: width,
      height: height,
      // color: Colors.black38,
    );
    //网络图片
    if (!url.contains('assets/')) {
      child = _buildNet();
    }
    //本地图片
    if (url.contains('assets/') && !url.contains('http')) {
      child = _buildImg(context);
    }

    //本地图片
    if (url.contains('assets/') && url.contains('.svg')) {
      child = _buildSvg(context);
    }

    child = ClipRRect(
      borderRadius: borderRadius ?? BorderRadius.circular(radius),
      child: child,
    );

    if (onTap != null) {
      child = InkWell(
        onTap: () => onTap!(),
        child: ClipRRect(
          borderRadius: borderRadius ?? BorderRadius.circular(radius),
          child: child,
        ),
      );
    }

    return child;
  }

  Widget _buildNet() {
    if (useEncrypt && headers == null) {
      return Stack(
        children: <Widget>[
          failedWidget ??
              const VectorGraphic(
                loader: AssetBytesLoader(
                  Res.imagesUserSplashCenter,
                ),
                colorFilter: ColorFilter.mode(
                  Colors.black38,
                  BlendMode.srcIn,
                ),
              ),
          const Text(
            'Using encrypt the headers must no null',
            style: TextStyle(
              color: Colors.red,
            ),
          ),
        ],
      );
    }

    return ExtendedImage(
      image: ExtendedResizeImage.resizeIfNeeded(
        provider: ImgExNetworkProvider(
          url,
          cache: true,
          useEncrypt: useEncrypt,
          headers: headers,
          always: always,
        ),
      ),
      border: border,
      borderRadius: borderRadius ?? BorderRadius.all(Radius.circular(radius)),
      loadStateChanged: (state) {
        switch (state.extendedImageLoadState) {
          case LoadState.loading:
            return SizedBox(
              width: width,
              height: height,
              child: Center(
                child: loadingWidget ??
                    const Opacity(
                      opacity: 0.3,
                      child: VectorGraphic(
                        loader: AssetBytesLoader(
                          Res.imagesUserVideoDefaultBackground,
                        ),
                      ),
                    ),
              ),
            );
          case LoadState.completed:
            final image = state.extendedImageInfo?.image;

            // 组件宽度
            final imageWidth = (image?.width ?? 0).toDouble();

            // 组件高度
            final imageHeight = (image?.height ?? 0).toDouble();

            final meets = imageWidth / imageHeight <= aspectRatio;

            if (aspectRatio != 0) {
              if (meets) {
                return ExtendedRawImage(
                  image: image,
                  width: double.infinity,
                  height: double.infinity,
                  fit: BoxFit.cover,
                );
              } else {
                return ExtendedRawImage(
                  image: image,
                  width: double.infinity,
                  fit: BoxFit.fitWidth,
                );
              }
            } else {
              return ExtendedRawImage(
                image: image,
                width: width,
                height: height,
                fit: fit,
              );
            }

          case LoadState.failed:
            return GestureDetector(
              child: SizedBox(
                width: width,
                height: height,
                child: Center(
                  child: failedWidget ??
                      Opacity(
                        opacity: 0.3,
                        child: VectorGraphic(
                          loader: const AssetBytesLoader(
                            Res.imagesUserVideoDefaultBackground,
                          ),
                          width: width == null ? 102 : width! * 0.5,
                          fit: fit ?? BoxFit.contain,
                          colorFilter: const ColorFilter.mode(
                            Colors.black38,
                            BlendMode.srcIn,
                          ),
                        ),
                      ),
                ),
              ),
              onTap: () => state.reLoadImage(),
            );
        }
      },
    );
  }

  Widget _buildImg(BuildContext context) {
    return Image(
      image: AssetImage(url),
      width: width,
      height: height,
      fit: fit,
      color: color,
    );

    // //待 修复 貌似不支持GIF 用纹理图片 的好处是减少OOM
    // return BkFlutterImage(
    //   url: url,
    //   width: width,
    //   height: height,
    //   fit: fit!,
    //   //表示 占位图片资源
    //   placeholder: Res.imagesBgDef,
    //   //加载错误的时候使用一个 错误图
    //   imageErrorBuilder: (context, error, stackTrace) {
    //     return Image.asset(
    //       Res.imagesBgDef,
    //       width: width,
    //       height: height,
    //       fit: fit,
    //     );
    //   },
    // );
  }

  Widget _buildSvg(BuildContext context) {
    return VectorGraphic(
      loader: AssetBytesLoader(url),
      width: width,
      height: height,
      fit: fit ?? BoxFit.contain,
      colorFilter: const ColorFilter.mode(
        Colors.black38,
        BlendMode.srcIn,
      ),
    );
  }
}
